package com.aw.datajpa.service;

import com.aw.datajpa.constant.REnum;
import com.aw.datajpa.dao.StudentRepository;
import com.aw.datajpa.exception.RException;
import com.aw.datajpa.pojo.Student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;



import java.util.List;

@Service
public class StudentService {

    @Autowired
    public StudentRepository studentRepository;

    /**
     * 读所有的学生列表
     * @return List<Student>
     */
    public List<Student> getAll() {
        return studentRepository.findAll();
    }
    //新增
    public Student add(Student student) {
        return studentRepository.save(student);
    }
    //更新
    public Student update(  Student student) {
        return studentRepository.save(student);
    }
    //删除
    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }

    public Student validateUsernameAndPassword(String sno, String password) throws Exception {
        List<Student> students = studentRepository.findByName(sno);
        if (students.size() > 0) {
            // 可能对password加密，但我们暂时不做处理
            Student student = students.get(0);
            if (student.getPassword().equals(password)) {
                // 成功
                return student;
            } else {
                throw new RException(REnum.LOGIN_ERR);
            }
        } else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }
    public Student getById(Integer id) {
        return studentRepository.findById(id).get();
    }
    public Page<Student> getAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }
    public Page<Student> getAll(Example<Student> example, Pageable pageable) {
        return studentRepository.findAll(example, pageable);
    }
}